package com.endava.action;

import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.endava.dao.BookDAO;
import com.endava.dao.impl.BookDAOImpl;
import com.endava.model.Book;

public class UpdateBookAction extends HttpServlet {

	private static final long serialVersionUID = 1811884124107703588L;

	public void doPost(HttpServletRequest req, HttpServletResponse res) {
		String bookName = req.getParameter("name");
		String author = req.getParameter("author");
		String releaseDate = req.getParameter("releaseDate");

		if (bookName == null || bookName.isEmpty() || author == null
				|| author.isEmpty()) {
			Writer writer = null;
			try {
				writer = res.getWriter();
				writer.write("Please provide us the bookName and the author");
			} catch (IOException e) {
				System.out.println("Exception: " + e.getMessage());
			} finally {
				try {
					if (writer != null) {
						writer.close();
					}
				} catch (IOException e) {
					System.out.println("Error on closing the writer");
				}
			}
		} else {
			BookDAO bookDAO = new BookDAOImpl();
			((BookDAOImpl) bookDAO)
					.setConnection((Connection) getServletContext()
							.getAttribute("connection"));

			Book book = bookDAO.getBookById((Integer) req.getAttribute("id"));
			book.setAuthor(author);
			book.setName(bookName);
			book.setReleaseDate(releaseDate);

			bookDAO.update(book);
		}
	}

}
